package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;


@RestController("/pda")
public class PdaController {

    @Autowired
    private TOngoodsshelfMapper ongoodsshelfMapper;

    @Autowired
    private TBaseStorageAreaLocationMapper baseStorageAreaLocationMapper;

    @Autowired
    private TBaseStorageAreaLocationMapper mapper;

    @Autowired
    private TCkPickingwavegoodsMapper pickingwavegoodsMapper;


    @Autowired
    private TMiStockMapper tMiStockMapper;

    @Autowired
    private TMiStockBackMapper tMiStockBackMapper;


    @PostMapping("/getList")
    public AjaxResult list(@RequestBody PdaDomin pdaDomin) {

        String url = "http://192.168.103.210:8089/api/inListRK";
        String kanbanNo = pdaDomin.getKANBAN_NO();
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();
        // 创建请求体
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("KANBAN_NO", kanbanNo);
        // 发送 POST 请求
        ResponseEntity<Map> response = restTemplate.postForEntity(url, requestBody, Map.class);
       /* Map<String, Object> fakeData = new HashMap<>();
        fakeData.put("KANBAN_NO", "条码号");
        fakeData.put("SUPPLIER_LINE", "产线");
        fakeData.put("SUPPLIER_PART_NO", "型号");
        fakeData.put("KANBAN_QTY", "数量");
        fakeData.put("TRANSFER_DATE", "下线时间");
        return AjaxResult.success(fakeData);*/
        // 处理响应
        Map<String, Object> responseBody = response.getBody();
        if (responseBody != null && "0".equals(responseBody.get("CODE"))) {
            return AjaxResult.success(responseBody.get("DATA"));
        } else {
            return AjaxResult.error((String) responseBody.get("MESSAGE"));
        }
    }

    @PostMapping("/lists")
    public AjaxResult lists(@RequestBody PdaDomin pdaDomin) {
        String kanbanNo = pdaDomin.getKANBAN_NO();
        String jdbcUrl = "jdbc:oracle:thin:@//156.147.197.32:3001/TAMESP";
        String username = "hem_usr"; // 替换为您的数据库用户名
        String password = "hem12#usr"; // 替换为您的数据库密码

        Map<String, Object> resultData = new HashMap<>();

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
            String sql = "SELECT * FROM hem_usr.tb_knbn_out_inf WHERE KANBAN_NO = ?";
            try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                preparedStatement.setString(1, kanbanNo);
                ResultSet resultSet = preparedStatement.executeQuery();

                if (resultSet.next()) {
                    resultData.put("KANBAN_NO", resultSet.getString("KANBAN_NO"));
                    resultData.put("SUPPLIER_LINE", resultSet.getString("SUPPLIER_LINE"));
                    resultData.put("SUPPLIER_PART_NO", resultSet.getString("SUPPLIER_PART_NO"));
                    resultData.put("KANBAN_QTY", resultSet.getInt("KANBAN_QTY"));
                    resultData.put("TRANSFER_DATE", resultSet.getDate("TRANSFER_DATE"));
                    return AjaxResult.success(resultData);
                } else {
                    return AjaxResult.error("未找到相关数据");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("数据库查询失败: " + e.getMessage());
        }
    }

    @PostMapping("/getLocal")
    public AjaxResult filterLocationsBySecondAndThirdParts(@RequestBody TBaseStorageAreaLocation location) {
        List<LocalVo> locations = baseStorageAreaLocationMapper.getlist(location);
        List<LocalVo> local = locations.stream()
                .sorted(Comparator.comparing(LocalVo::getSort)) // 根据 sort 属性排序
                .collect(Collectors.toList());
        // 假设 LocalVo 类有一个 getSort() 方法
        List<LocalVo> collect = locations.stream()
                .filter(localVo -> localVo.getBarcode() != null && !localVo.getBarcode().equals(""))
                .sorted(Comparator.comparing(LocalVo::getSort)) // 根据 sort 属性排序
                .collect(Collectors.toList());
        if (!collect.isEmpty()) {
            return AjaxResult.success(collect);
        }
        return AjaxResult.success(local);
    }

    /**
     * pad 新增任务
     *
     * @param pdaDomin
     * @return
     */

    @PostMapping("/add")
    public AjaxResult add(@RequestBody PdaDomin pdaDomin) {
        if (pdaDomin.getLocal() != null && !pdaDomin.getLocal().isEmpty()) {
            TOngoodsshelf on = new TOngoodsshelf();
            on.setLocationId(pdaDomin.getLocal());
            List<TOngoodsshelf> tOngoodsshelves = ongoodsshelfMapper.selectTOngoodsshelfList(on);
            if (!tOngoodsshelves.isEmpty()) {
                throw new RuntimeException("改库位当前有入库任务，请检查库位");
            }
            TCkPickingwavegoods ps = new TCkPickingwavegoods();
            ps.setLocId(pdaDomin.getLocal());
            List<TCkPickingwavegoods> list = pickingwavegoodsMapper.selectTCkPickingwavegoodsList(ps);
            ps.setLocId(pdaDomin.getLocal());
            if (!list.isEmpty()) {
                throw new RuntimeException("库位当前有出库或移库任务，请检查库位");
            }
            TBaseStorageAreaLocation one = baseStorageAreaLocationMapper.getOne(pdaDomin.getLocal());
            if (!one.getSTATUS().equals("0")) {
                throw new RuntimeException("请检查所选库位状态");

            }
            LambdaQueryWrapper<TMiStock> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TMiStock::getLocationId, pdaDomin.getLocal());
            if (!tMiStockMapper.selectList(wrapper).isEmpty())
                throw new RuntimeException("当前库位已经存在库存请重新选择");
        }
        //获取id
        Long PICID = ongoodsshelfMapper.getNextSequenceValue();

        TOngoodsshelf ongoodsshelf = new TOngoodsshelf();
        //产线
        ongoodsshelf.setGropSc(pdaDomin.getSUPPLIER_LINE());

        //型号
        ongoodsshelf.setBARCODE(pdaDomin.getSUPPLIER_PART_NO());

        ongoodsshelf.setShelfNum(pdaDomin.getKANBAN_QTY());
        ongoodsshelf.setCTL(pdaDomin.getKANBAN_NO());
        ongoodsshelf.setDecid("1");
        ongoodsshelf.setStatus("0");
        ongoodsshelf.setProductionDate(pdaDomin.getTRANSFER_DATE());
        ongoodsshelf.setONDATE(new Date());
        ongoodsshelf.setPlcID(PICID);
        //写入时间
        ongoodsshelf.setGOODSID(pdaDomin.getKANBAN_NO());
        ongoodsshelf.setLotId(generateTimestampCode());
        ongoodsshelf.setGOODSNAME(pdaDomin.getGoodsName());
        ongoodsshelf.setLocationId(pdaDomin.getLocal());
        ongoodsshelfMapper.insertTOngoodsshelf(ongoodsshelf);
        String local = pdaDomin.getLocal();

        if (local != null && !local.isEmpty()) {
            TBaseStorageAreaLocation tBaseStorageAreaLocation = new TBaseStorageAreaLocation();
            tBaseStorageAreaLocation.setLocationId(local);
            tBaseStorageAreaLocation.setSTATUS("1");
            mapper.updateTBaseStorageAreaLocation(tBaseStorageAreaLocation);
        }


        return AjaxResult.success();
    }


    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/out")
    @Log(title = "pad手动出库")
    public AjaxResult out(@RequestBody TMiStock tMiStock) {
        List<TMiStock> tMiStocks = tMiStockMapper.selectTMiStockList(tMiStock);

        for (TMiStock miStock : tMiStocks) {
            // Check if the quantities are the same
            String[] incomingSplit = tMiStock.getShelvesNum().split("\\.");
            if (incomingSplit[0].equals(tMiStock.getShelvesNum())) {
                // Delete stock
                int deleteResult = tMiStockMapper.deleteTMiStockByPutinId(miStock.getPutinId());
                if (deleteResult == 0) {
                    return AjaxResult.error("出库失败");
                }

                TMiStockBack back = new TMiStockBack();
                BeanUtils.copyProperties(miStock, back);
                back.setGoodsNum(tMiStock.getShelvesNum());
                // Insert into backup
                int insertResult = tMiStockBackMapper.insertTMiStockBack(back);
                if (insertResult == 0) {
                    return AjaxResult.error("备份失败");
                }

                // Release storage location
                TBaseStorageAreaLocation location = new TBaseStorageAreaLocation();
                location.setLocationId(miStock.getLocationId());
                location.setSTATUS("0");
                int updateResult = baseStorageAreaLocationMapper.updateTBaseStorageAreaLocation(location);
                if (updateResult == 0) {
                    return AjaxResult.error("库位释放失败");
                }
            }else {
                return AjaxResult.error("未找到库存");
            }
        }

        return AjaxResult.success("出库成功");
    }

    private String generateTimestampCode() {
        String prefix = "RK";
        long timestamp = System.currentTimeMillis(); // 获取当前时间戳
        String rfid = prefix + timestamp;
        return rfid;
    }


}
